package com.zl.codereview;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.zl.codereview.util.IdeaUtils;
import com.zl.codereview.util.JOptionPaneUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;

public class GitBashAction  extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        try {
            String path = IdeaUtils.getModuleFilePath(e);
            String gitPath = findGitInPath();
            // 创建ProcessBuilder对象
            ProcessBuilder processBuilder = new ProcessBuilder(gitPath+"\\git-bash.exe");
            // 设置启动目录（可选）
            processBuilder.directory(new File(path));
            // 启动进程
            processBuilder.start();
        } catch (Exception e1) {
            e1.printStackTrace();
            JOptionPaneUtils.warn(e1.getMessage());
        }
    }

    private static String findGitInPath() {
        String pathEnv = System.getenv("PATH");
        String[] paths = pathEnv.split(File.pathSeparator);
        for (String path : paths) {
            if(path.contains("Git")){
                return path.substring(0,path.indexOf("Git")+3);
            }else if(path.contains("git")){
                return path.substring(0,path.indexOf("git")+3);
            }
        }
        return "C:\\Program Files\\Git";
    }
}
